<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>

    <canvas id="cvs" width="500px" height="500px"></canvas>
    <script>
        // 获取canvas
        const oCanvs = document.querySelector('#cvs');
        // 获取上下文环境
        const cvs = oCanvs.getContext('2d');
        // 画布宽高
        var w = h = 500;

        // 小球基本属性
        //  * show（）显示小球
        //  * move（）小球运动，碰撞检测
        //  * setIterval（）
        //  * for循环，生成多个实例化小球

        // arc(x,y,radius,startAngle,endAngle,boolean)
        function Ball (x,y,radius,color,xSpeed,ySpeed){
            this.x = rand(5) + 50;
            this.y = rand(5) + 50;
            this.r = rand(40) + 10;
            this.color = randColor();
            this.xSpeed = rand(3) + 2;
            this.ySpeed = rand(3) + 1;
        }

        Ball.prototype.show = function (){
            // 开启新路径
            cvs.beginPath();
            cvs.arc(this.x,this.y,this.r,0,Math.PI*2);
            cvs.fillStyle = this.color;
            // 确认填充
            cvs.fill();
            // 确认上色
            cvs.stroke();
        }

        Ball.prototype.move = function(){
            // 碰撞检测
            if(this.x + this.r >= w || this.x - this.r <= 0){
                this.xSpeed = -this.xSpeed;
            }
            this.x = this.x + this.xSpeed;
            if(this.y + this.r >= h || this.y - this.r <= 0){
                this.ySpeed = -this.ySpeed;
            }
            this.y = this.y + this.ySpeed;
        }


        let ballArr = [];
        for(let i = 0;i < 30;i++){
            let ball = new Ball();
            ballArr.push(ball);
            ball.show();
        }


        setInterval(function (){
            // 每次移动需要清除上一快画布
            cvs.clearRect(0,0,w,h)
            for(let j = 0; j< ballArr.length;j++){
                let ballls = ballArr[j];
                ballls.show();
                ballls.move();
            }
        },10)




        function rand (num){
            return parseInt(Math.random() * num);
        }

        function randColor(){
            let a = rand(255);
            let b = parseInt(Math.random() * 255);
            let c = parseInt(Math.random() * 255);
            return `rgb(${a},${b},${c})`;
        }
         
    </script>
</body>
</html>